package com.xianyuwangyou.taizhangdengji

import android.content.Context
import android.os.Build
import android.os.Environment
import com.google.gson.Gson
import java.io.File
import java.io.InputStreamReader
import java.io.OutputStreamWriter


class ConfigDataManager private constructor() {
    private var configData: ConfigData? = null
    private var productsWithSecondaries: MutableList<ProductWithSecondaries> = mutableListOf()

    companion object {
        @Volatile
        private var INSTANCE: ConfigDataManager? = null

        fun getInstance(): ConfigDataManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: ConfigDataManager().also { INSTANCE = it }
            }
        }
    }
    
    // 获取应用外部存储配置文件路径（真正的持久化存储）
    private fun getExternalConfigFile(context: Context): File {
        // 使用现代方式获取外部存储目录，适配Android 10及以上版本
        // 确保使用外部公共目录，这样即使应用被卸载，数据也会保留
        val externalDir = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // 在Android 10及以上版本中，使用外部公共目录确保数据持久性
            val externalPublicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
            File(externalPublicDir, "TaizhangDengji")
        } else {
            // Android 9及以下版本
            File(Environment.getExternalStorageDirectory(), "TaizhangDengji")
        }
        
        if (!externalDir.exists()) {
            externalDir.mkdirs()
        }
        return File(externalDir, "config.json")
    }
    
    // 获取应用特定外部存储配置文件路径（会随应用卸载而删除）
    private fun getAppSpecificExternalConfigFile(context: Context): File {
        // 使用应用特定的外部存储目录
        val externalDir = File(context.getExternalFilesDir(null), "data")
        if (!externalDir.exists()) {
            externalDir.mkdirs()
        }
        return File(externalDir, "config.json")
    }

    fun loadConfigData(context: Context) {
        try {
            // 首先尝试从应用外部存储加载配置数据
            val externalFile = getExternalConfigFile(context)
            if (externalFile.exists()) {
                val inputStream = externalFile.inputStream()
                val reader = InputStreamReader(inputStream)
                val gson = Gson()
                configData = gson.fromJson(reader, ConfigData::class.java)
                reader.close()
            } else {
                // 如果应用外部存储中没有配置文件，则尝试从应用特定外部存储加载
                val appSpecificExternalFile = getAppSpecificExternalConfigFile(context)
                if (appSpecificExternalFile.exists()) {
                    val inputStream = appSpecificExternalFile.inputStream()
                    val reader = InputStreamReader(inputStream)
                    val gson = Gson()
                    configData = gson.fromJson(reader, ConfigData::class.java)
                    reader.close()
                    
                    // 将数据迁移到应用外部存储
                    saveConfigDataToFile(context)
                    
                    // 删除应用特定外部存储的旧文件
                    try {
                        appSpecificExternalFile.delete()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                } else {
                    // 如果应用特定外部存储中没有配置文件，则尝试从内部存储加载（备份恢复的数据）
                    try {
                        val inputStream = context.openFileInput("config.json")
                        val reader = InputStreamReader(inputStream)
                        val gson = Gson()
                        configData = gson.fromJson(reader, ConfigData::class.java)
                        reader.close()
                        
                        // 将数据迁移到应用外部存储
                        saveConfigDataToFile(context)
                        
                        // 删除内部存储的旧文件
                        try {
                            context.deleteFile("config.json")
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    } catch (internalException: Exception) {
                        // 如果内部存储中没有配置文件，则从assets目录加载
                        try {
                            val inputStream = context.assets.open("config.json")
                            val reader = InputStreamReader(inputStream)
                            val gson = Gson()
                            configData = gson.fromJson(reader, ConfigData::class.java)
                            reader.close()
                            
                            // 将数据保存到应用外部存储
                            saveConfigDataToFile(context)
                        } catch (assetsException: Exception) {
                            assetsException.printStackTrace()
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    private fun saveConfigDataToFile(context: Context) {
        try {
            val gson = Gson()
            val json = gson.toJson(configData)
            
            // 保存到外部存储（用户数据持久化）
            val externalFile = getExternalConfigFile(context)
            val writer = OutputStreamWriter(externalFile.outputStream())
            writer.write(json)
            writer.close()
            
            // 同时保存到内部存储（用于备份功能）
            val internalWriter = OutputStreamWriter(context.openFileOutput("config.json", Context.MODE_PRIVATE))
            internalWriter.write(json)
            internalWriter.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    // 添加更新整个配置数据的方法
    fun updateConfigData(context: Context, newConfigData: ConfigData) {
        configData = newConfigData
        saveConfigDataToFile(context)
    }

    fun getMarketers(): List<String> {
        return configData?.marketers ?: emptyList()
    }

    fun getProducts(): List<String> {
        return configData?.products?.map { it.name } ?: emptyList()
    }
    
    // 获取带二级产品的完整产品列表
    fun getProductsWithSecondaries(): List<ProductWithSecondaries> {
        return configData?.products ?: emptyList()
    }
    
    // 添加营销人
    fun addMarketer(context: Context, marketer: String) {
        val currentMarketers = configData?.marketers?.toMutableList() ?: mutableListOf()
        if (!currentMarketers.contains(marketer)) {
            currentMarketers.add(marketer)
            configData = ConfigData(currentMarketers, configData?.products ?: emptyList())
            saveConfigDataToFile(context)
        }
    }
    
    // 删除营销人
    fun removeMarketer(context: Context, marketer: String) {
        val currentMarketers = configData?.marketers?.toMutableList() ?: mutableListOf()
        if (currentMarketers.contains(marketer)) {
            currentMarketers.remove(marketer)
            configData = ConfigData(currentMarketers, configData?.products ?: emptyList())
            saveConfigDataToFile(context)
        }
    }
    
    // 添加产品
    fun addProduct(context: Context, product: String) {
        val currentProducts = configData?.products?.toMutableList() ?: mutableListOf()
        if (!currentProducts.any { it.name == product }) {
            currentProducts.add(ProductWithSecondaries(product))
            configData = ConfigData(configData?.marketers ?: emptyList(), currentProducts)
            saveConfigDataToFile(context)
        }
    }
    
    // 删除产品
    fun removeProduct(context: Context, product: String) {
        val currentProducts = configData?.products?.toMutableList() ?: mutableListOf()
        if (currentProducts.any { it.name == product }) {
            currentProducts.removeAll { it.name == product }
            configData = ConfigData(configData?.marketers ?: emptyList(), currentProducts)
            saveConfigDataToFile(context)
        }
    }
    
    // 为指定产品添加二级产品
    fun addSecondaryProduct(context: Context, productName: String, secondaryName: String) {
        val currentProducts = configData?.products?.toMutableList() ?: mutableListOf()
        val productIndex = currentProducts.indexOfFirst { it.name == productName }
        
        if (productIndex != -1) {
            val product = currentProducts[productIndex]
            val secondaries = product.secondaries.toMutableList()
            
            // 检查是否已存在相同的二级产品
            if (!secondaries.any { it.name == secondaryName }) {
                secondaries.add(SecondaryProduct(secondaryName))
                val updatedProduct = product.copy(secondaries = secondaries)
                currentProducts[productIndex] = updatedProduct
                configData = ConfigData(configData?.marketers ?: emptyList(), currentProducts)
                saveConfigDataToFile(context)
            }
        } else {
            // 如果产品不存在，创建新产品并添加二级产品
            val newProduct = ProductWithSecondaries(
                productName,
                mutableListOf(SecondaryProduct(secondaryName))
            )
            currentProducts.add(newProduct)
            configData = ConfigData(configData?.marketers ?: emptyList(), currentProducts)
            saveConfigDataToFile(context)
        }
    }
    
    // 删除指定产品的二级产品
    fun removeSecondaryProduct(context: Context, productName: String, secondaryName: String) {
        val currentProducts = configData?.products?.toMutableList() ?: mutableListOf()
        val productIndex = currentProducts.indexOfFirst { it.name == productName }
        
        if (productIndex != -1) {
            val product = currentProducts[productIndex]
            val secondaries = product.secondaries.toMutableList()
            secondaries.removeAll { it.name == secondaryName }
            
            val updatedProduct = product.copy(secondaries = secondaries)
            currentProducts[productIndex] = updatedProduct
            configData = ConfigData(configData?.marketers ?: emptyList(), currentProducts)
            saveConfigDataToFile(context)
        }
    }
    
    // 获取指定产品下的所有二级产品
    fun getSecondaryProducts(productName: String): List<String> {
        val product = configData?.products?.find { it.name == productName }
        return product?.secondaries?.map { it.name } ?: emptyList()
    }
}